package com.demo.queue;

import java.util.Scanner;

/**
 * 队列 用数组模拟
 * 包括添加元素、展示队列、从队列取数据等  （只能用一次）
 */
public class ArrayQueue {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String inputStr = "";
        boolean loop = true;
        Queue queue = new Queue(3);
        while (loop) {
            System.out.println("s:展示队列中的所有元素");
            System.out.println("a:添加元素");
            System.out.println("g:获取元素");
            System.out.println("e:退出模拟");
            inputStr = scanner.nextLine();
            switch (inputStr) {
                case "a":
                    queue.addElement(scanner.nextInt());
                    break;
                case "s":
                    queue.showQueue();
                    break;
                case "e":
                    scanner.close();
                    loop = false;
                    break;
                case "g":
                    queue.getElement();
                    break;
                default:
                    break;
            }
        }
    }
}

class Queue {
    private int maxSize;

    private int[] arr;

    private int front = -1;

    private int real = -1;

    /**
     *  初始化队列
     * @param maxSize
     */
    public Queue(int maxSize) {
        System.out.printf("创建一个容量大小为%d的数组队列", maxSize);
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
    }

    /**
     * 队列是否已满
     * @return
     */
    public boolean isFull() {
        return real == maxSize - 1;
    }

    /**
     * 队列是否为空
     * @return
     */
    public boolean isEmpty() {
        return front == real;
    }

    /**
     * 添加元素
     * @param element
     */
    public void addElement(int element) {
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }
        real++;
        arr[real] = element;
        System.out.println("新增后real为：" + real);
    }

    /**
     * 获取元素
     */
    public void getElement() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        front++;
        System.out.printf("获取队列值为：%d\n", arr[front]);
    }

    /**
     * 展示队列
     */
    public void showQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        while (front < real) {
            front++;
            System.out.println(arr[front]);
        }
    }
}
